from django.shortcuts import render, HttpResponseRedirect
from django.http.response import HttpResponse
from django.contrib.auth import login, logout, authenticate
from django.core.urlresolvers import reverse
from . import forms
# Create your views here.
from bbs import models
from . import common
import datetime

# 获取系统板块菜单
category_list = models.Category.objects.filter(set_as_top_menu=True).order_by('position_index')


def index(request):
    # 默认显示菜单posttion_index = 1的记录
    category_obj = models.Category.objects.get(position_index=1)
    article_list = models.Article.objects.filter(category=category_obj)
    # print(category_list, category_obj)
    return render(request, 'bbs/index.html', {'category_list': category_list,
                                              'category_obj': category_obj,
                                              'article_list': article_list})


def category(request, id):
    if id == '0':
        category_obj = models.Category.objects.get(position_index=1)
    else:
        category_obj = models.Category.objects.get(id=id)
    article_list = models.Article.objects.filter(category=category_obj, status='published')
    return render(request, 'bbs/index.html', {'category_list': category_list,
                                              'category_obj': category_obj,
                                              'article_list': article_list})


def acc_login(request):
    if request.method == 'POST':
        print(request.POST)
        print(request.path)
        user = authenticate(username=request.POST.get('username'),
                            password=request.POST.get('password'))
        if user is not None:
            # pass authentication
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            login_err = "用户名或密码错误"
            return render(request, 'login.html', {'login_err': login_err})
    return render(request, 'login.html', {'category_list': category_list})


def acc_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))


def article_detail(request, id):
    article_id = int(id)
    article_obj = models.Article.objects.get(id=article_id)
    common_list = article_obj.comment_set.select_related().filter(comment_type=1).order_by('parent_comment_id', 'date')
    commons = common.format_common_dict(common_list)
    return render(request, 'bbs/article_detail.html', {'article_obj': article_obj,
                                                       'category_list': category_list,
                                                       'common_list': commons})


def comment(request):
    """
    点赞和评论
    :param request:
    :return:
    """
    if request.method == "POST":
        article_obj = models.Article.objects.get(id=int(request.POST['article_id']))
        models.Comment.objects.create(article=article_obj,
                                      comment_type=int(request.POST['comment_type'][0]),
                                      comment=request.POST['saytext'],
                                      user=request.user.userprofile,
                                      parent_comment_id=int(request.POST['parent_comment_id']) if request.POST[
                                          'parent_comment_id'] else ''
                                      )
        print(request.POST)
    return HttpResponse('ok')


def pub_article(request):
    frm_article = forms.ArticleForm()
    if request.method == "POST":
        save_data = {}
        post_data = request.POST  # 获取所有post数据
        file_path = common.save_upload_file(request.FILES['head_img'])  # 保存文件
        print(post_data)
        save_data['title'] = post_data['title']
        save_data['brief'] = post_data['brief']
        save_data['author_id'] = request.user.userprofile.id
        save_data['category_id'] = int(post_data['category'])
        save_data['head_img'] = file_path
        save_data['content'] = post_data['content']
        save_data['status'] = post_data['status']
        save_data['pub_date'] = datetime.datetime.now()
        print(save_data)

        article_obj = models.Article(**save_data)
        article_obj.save()
        return HttpResponseRedirect(reverse('index'))

    return render(request, 'bbs/pub_article.html', {'category_list': category_list,
                                                    'frm_atricle': frm_article})
